from config.db_connection import DBConnection
import pymysql

class UserInfo:
    """用户信息数据类"""
    
    def __init__(self, user_data=None):
        """初始化用户信息"""
        if user_data:
            self.id = user_data.get('id', 0)
            self.username = user_data.get('username', '')
            self.phone = user_data.get('phone', '')
            self.gender = user_data.get('gender', '未设置')
            self.age = user_data.get('age', 0)
            self.role = user_data.get('role', 1)  # 1:普通用户, 0:管理员
        else:
            self.id = 0
            self.username = ''
            self.phone = ''
            self.gender = '未设置'
            self.age = 0
            self.role = 1
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'username': self.username,
            'phone': self.phone,
            'gender': self.gender,
            'age': self.age,
            'role': self.role
        }
    
    def get_role_name(self):
        """获取角色名称"""
        return "管理员" if self.role == 0 else "普通用户"
    
    def get_age_display(self):
        """获取年龄显示文本"""
        return str(self.age) if self.age > 0 else '未设置'
    
    def is_admin(self):
        """判断是否为管理员"""
        return self.role == 0
    
    def update_from_dict(self, data):
        """从字典更新数据"""
        if 'username' in data:
            self.username = data['username']
        if 'gender' in data:
            self.gender = data['gender']
        if 'age' in data:
            self.age = data['age']
    
    def __str__(self):
        """字符串表示"""
        return f"UserInfo(id={self.id}, username='{self.username}', role={self.get_role_name()})"

class UserModel:
    """用户数据模型"""
    
    @staticmethod
    def authenticate(phone, password):
        """验证用户身份并返回 UserInfo 对象"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 根据手机号查询用户（包含所有字段）
            cursor.execute("""
                SELECT id, username, password, gender, age, role 
                FROM user WHERE telephone = %s
            """, (phone,))
            user = cursor.fetchone()
            
            if user and user[2] == password:  # user[2] 是密码字段
                user_data = {
                    'id': user[0],
                    'username': user[1],
                    'phone': phone,
                    'gender': user[3],
                    'age': user[4],
                    'role': user[5]
                }
                user_info = UserInfo(user_data)
                print(f"{user_info.get_role_name()} {user_info.username} 登录成功")
                return user_info
            else:
                print(f"手机号 {phone} 登录失败：用户不存在或密码错误")
                return None
                
        except pymysql.Error as e:
            print(f"登录验证失败: {e}")
            return None
        finally:
            cursor.close()
    
    @staticmethod
    def register_user(phone, password):
        """
        注册新用户（默认为普通用户，role=1）
        Args:
            phone: 手机号
            password: 密码
        Returns:
            bool: 注册是否成功
        """
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 检查手机号是否已存在
            cursor.execute("SELECT id FROM user WHERE telephone = %s", (phone,))
            if cursor.fetchone():
                print(f"手机号 {phone} 已注册")
                return False
            
            # 插入新用户并获取自增ID（默认role=1，普通用户）
            sql = """
                INSERT INTO user (username, password, telephone, role) 
                VALUES ('临时用户名', %s, %s, 1)
            """
            cursor.execute(sql, (password, phone))
            user_id = cursor.lastrowid  # 获取刚插入记录的ID
            
            # 更新用户名
            username = f"用户{user_id}"
            cursor.execute("UPDATE user SET username = %s WHERE id = %s", 
                         (username, user_id))
            
            conn.commit()
            print(f"普通用户注册成功，用户名为: {username}")
            return True
            
        except pymysql.Error as e:
            print(f"注册用户失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def reset_password(phone, new_password):
        """重置用户密码"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 检查手机号是否存在
            cursor.execute("SELECT id FROM user WHERE telephone = %s", (phone,))
            if not cursor.fetchone():
                print(f"手机号 {phone} 不存在")
                return False
            
            # 更新密码
            cursor.execute("UPDATE user SET password = %s WHERE telephone = %s", 
                         (new_password, phone))
            
            conn.commit()
            print(f"手机号 {phone} 密码重置成功")
            return True
            
        except pymysql.Error as e:
            print(f"重置密码失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def get_user_info(user_id):
        """根据用户ID获取 UserInfo 对象"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("""
                SELECT id, username, telephone, gender, age, role 
                FROM user WHERE id = %s
            """, (user_id,))
            
            user = cursor.fetchone()
            if user:
                user_data = {
                    'id': user[0],
                    'username': user[1],
                    'phone': user[2],
                    'gender': user[3],
                    'age': user[4],
                    'role': user[5]
                }
                return UserInfo(user_data)
            else:
                print(f"用户ID {user_id} 不存在")
                return None
                
        except pymysql.Error as e:
            print(f"获取用户信息失败: {e}")
            return None
        finally:
            cursor.close()
    
    @staticmethod
    def update_user_info(user_id, username=None, gender=None, age=None):
        """更新用户信息"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 构建动态更新SQL
            update_fields = []
            params = []
            
            if username is not None:
                update_fields.append("username = %s")
                params.append(username)
            
            if gender is not None:
                update_fields.append("gender = %s")
                params.append(gender)
            
            if age is not None:
                update_fields.append("age = %s")
                params.append(age)
            
            if not update_fields:
                print("没有需要更新的字段")
                return False
            
            # 添加用户ID到参数列表
            params.append(user_id)
            
            # 执行更新
            sql = f"UPDATE user SET {', '.join(update_fields)} WHERE id = %s"
            cursor.execute(sql, tuple(params))
            
            conn.commit()
            print(f"用户信息更新成功")
            return True
            
        except pymysql.Error as e:
            print(f"更新用户信息失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def is_admin(user_data):
        """判断用户是否为管理员"""
        return user_data and user_data.get('role') == 0
    
    @staticmethod
    def get_role_name(role):
        """获取角色名称"""
        role_names = {0: '管理员', 1: '普通用户'}
        return role_names.get(role, '未知角色')